package main

import (
	"encoding/binary"
	"fmt"
	"unsafe"
)

// 64 位操作系统 8 bytes
const int_size = int(unsafe.Sizeof(0))

// 判断我们系统中使用的字节序
func systemEndian() {
	var i = 0x01020304
	fmt.Println("&i:", &i)
	bs := (*[int_size]byte)(unsafe.Pointer(&i))
	if bs[0] == 0x04 {
		// bs 的低位存放了i的低位， 那就是小短序
		fmt.Println("system endian is little endian")
	} else {
		fmt.Println("system endian is big endian")
	}
	fmt.Printf("temp: 0x%x, %v\n", bs[0], &bs[0])
	fmt.Printf("temp: 0x%x, %v\n", bs[1], &bs[1])
	fmt.Printf("temp: 0x%x, %v\n", bs[2], &bs[2])
	fmt.Printf("temp: 0x%x, %v\n", bs[3], &bs[3])
}

// 测试大端序
func testBigEndian() {
	var testInt int32 = 0x01020304
	fmt.Printf("%d use big endian: \n", testInt)
	testBytes := make([]byte, 4)
	// 将testInt 放入testBytes中， 并按照大端排序
	binary.BigEndian.PutUint32(testBytes, uint32(testInt))
	fmt.Println("int32 to bytes:", testBytes)
	fmt.Printf("int32 to bytes: %x \n", testBytes)

	convInt := binary.BigEndian.Uint32(testBytes)
	fmt.Printf("types to uint32: %d \n", convInt)
	fmt.Printf("types to hex: %0x \n\n", convInt)
}

func testLittleEndian() {
	var testInt int32 = 0x01020304
	fmt.Printf("%x use little endian \n", testInt)
	testBytes := make([]byte, 4)
	binary.LittleEndian.PutUint32(testBytes, uint32(testInt))
	fmt.Printf("int32 to bytes: %x \n", testBytes)
	convInt := binary.LittleEndian.Uint32(testBytes)
	fmt.Printf("bytes to int32: %d \n\n", convInt)
}

func main() {
	systemEndian()
	fmt.Println("")
	testBigEndian()
	testLittleEndian()
}
